from fastapi import APIRouter, Depends, status
from pydantic import BaseModel

from conf import variable
from dependencies import get_current_user
from utils.taxonomy_util import TaxonomyUtil

router = APIRouter(prefix=variable.CONTEXT_PATH + '/tree',
                   tags=['tree'],
                   dependencies=[Depends(get_current_user)])


def build_tree_data():
    data = []
    with open('data/chest_deep_taxonomy_2021_07_15.txt', 'r', encoding='UTF-8') as f:
        lines = f.readlines()
        for i in lines:
            data.append(i.strip())
    data.reverse()
    return TaxonomyUtil().build_tree(data)


data = build_tree_data()


@router.post('/get_base_taxonomy')
async def get_base_taxonomy():
    payload = {'data': data}

    return {'code': status.HTTP_200_OK, 'message': '', 'payload': payload}


class SearchByIdItem(BaseModel):
    id: int
    checked_keys: list


@router.post('/search_by_id')
async def search_by_id(item: SearchByIdItem):
    recursive_list = TaxonomyUtil.search_by_id(data, item.id)

    for i, j in enumerate(data):
        if recursive_list[0] == j['id']:
            head_node_index = i
            break

    # 用户选择正常
    if data[head_node_index]['children'][0]['id'] == recursive_list[1]:
        start_id = data[head_node_index]['children'][1]['id']
        if head_node_index == len(data) - 1:
            end_id = 5000
        else:
            end_id = data[head_node_index + 1]['id']
        exclusive_list = [i for i in range(start_id, end_id)]
    # 用户选择异常
    else:
        exclusive_list = [data[head_node_index]['children'][0]['id']]

    new_checked_id_list = item.checked_keys + recursive_list
    new_checked_id_list = list(set(new_checked_id_list) - set(exclusive_list))
    return {'code': status.HTTP_200_OK, 'message': '',
            'payload': {'new_checked_id_list': new_checked_id_list}}
